package com.simba.system.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.simba.response.Result;
import com.simba.response.ResultCode;
import com.simba.system.entity.Role;
import com.simba.system.entity.User;
import com.simba.system.mapper.RoleMapper;
import com.simba.system.mapper.UserMapper;
import com.simba.system.service.OceanUserDetailService;
import com.simba.system.service.UserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.simba.utils.JwtTokenUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 用户信息表 服务实现类
 * </p>
 *
 * @author 陈俊 1002471284@qq.com
 * @since 2021-03-24
 */
@Slf4j
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Resource
    private UserMapper userMapper;

    @Resource
    private RoleMapper roleMapper;

    @Autowired
    private OceanUserDetailService oceanUserDetailService;

    @Autowired
    private PasswordEncoder passwordEncoder(){ return new BCryptPasswordEncoder(); };

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Value("${jwt.tokenHead}")
    private String TokenHead;

    @Override
    public Result login(String username, String password, String code, HttpServletRequest request) {
        String captcha = (String) request.getSession().getAttribute("captcha");
        if(StrUtil.isEmpty(code) || !captcha.equalsIgnoreCase(code)){
            return Result.error().message("验证码错误，请重新输入!");
        }
        UserDetails userDetails = oceanUserDetailService.loadUserByUsername(username);
        log.info("UserServiceImpl执行到这里了吗？" + userDetails.toString());
        if (null == userDetails || !passwordEncoder().matches(password, userDetails.getPassword())) {
            return Result.error(ResultCode.USER_ACCOUNT_OR_PASSWORD_ERROR);
        }
        if (!userDetails.isEnabled()) {
            return Result.error(ResultCode.USER_ACCOUNT_DISABLE);
        }
        log.info("开始更新security对象:"+userDetails.getAuthorities().toString());
        //更新security中的登录对象
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        //生成用户token
        log.info("更新完毕security对象，开始生成token");
        String token = jwtTokenUtil.generateToken(userDetails);
        Map<String, String> tokenmap = new HashMap<>();
        tokenmap.put("token", token);
        tokenmap.put("tokenHead", TokenHead);
        return Result.success().data("records", tokenmap);
    }

    @Override
    public User getUserByUsername(String username) {
        return userMapper.getUserByUsername(username);
    }

    /**
     * 根据用户的id去查询所属的角色
     * @param userId
     * @return
     */
    @Override
    public List<Role> getRoles(Long userId) {
        return roleMapper.getRoles(userId);
    }
}